package View.Cadastros;

import Model.UsuarioModel;
import Repositories.UsuarioRepository;
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.netbeans.lib.awtextra.AbsoluteLayout;

/**
 *
 * @author Yanne
 */
public class CadastroUsuario extends javax.swing.JDialog {

    UsuarioRepository usuarioRepository = new UsuarioRepository();
    int IdUsuario = 0;
    boolean editar = false;

    /** Creates new form CadastroUsuario */
    public CadastroUsuario(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
        this.setLocationRelativeTo(null);

        initComponents();

        AbsoluteLayout absoluto = null;
        jPanel1.setLayout(absoluto);

        //bg novo usuario?
        JLabel novouser = new JLabel(new ImageIcon("./img/bg_novo_usuario.png"));
        jPanel1.add(novouser);
        novouser.setBounds(0, 0, 350, 400);

        Enter();
        this.setLocationRelativeTo(null);
       // this.setResizable(false);  //pb aqui se ficar true, a jpainel fica maior que a png

    }

    public CadastroUsuario(java.awt.Dialog parent, boolean modal, int IdUsuario) {
        super(parent, modal);
        initComponents();

        AbsoluteLayout absoluto = null;
        jPanel1.setLayout(absoluto);

        //bg novo usuario?
        JLabel novouser = new JLabel(new ImageIcon("./img/bg_alterar_usuario.png"));
        jPanel1.add(novouser);
        novouser.setBounds(0, 0, 350, 400);

        Enter();
        this.IdUsuario = IdUsuario;
        IniciarUsuario();

        this.editar = true;
        this.setLocationRelativeTo(null);
        //this.setResizable(false);  //pb aqui se ficar true, a jpainel fica maior que a png

    }

    //Metodo utilizado para quando a tecla enter for apertado funcionar com TAB
    private void Enter() {
        HashSet conj = new HashSet(txtNome.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
        conj.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0));
        txtNome.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, conj);

        HashSet conj2 = new HashSet(txtLogin.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
        conj2.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0));
        txtLogin.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, conj2);

        HashSet conj3 = new HashSet(txtSenha.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
        conj3.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0));
        txtSenha.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, conj3);
    }

    //Metodo que coloca todos os campos de usuario nos jtextfield na hora da edição.
    private void IniciarUsuario() {
        UsuarioModel usuario = usuarioRepository.getUsuario(this.IdUsuario);
        if (usuario != null) {
            txtNome.setText(usuario.getUSUARIO_NOME());
            txtLogin.setText(usuario.getUSUARIO_LOGIN());
            txtSenha.setText(usuario.getUSUARIO_SENHA());
        }
    }

    private boolean ChecarCampos() {
        if (txtNome.equals("")) {
            JOptionPane.showMessageDialog(null, "É obrigatório preencher o campo Nome!");
            return false;
        } else if (txtLogin.equals("")) {
            JOptionPane.showMessageDialog(null, "É obrigatório preencher o campo Login!");
            return false;
        } else if (txtSenha.equals("")) {
            JOptionPane.showMessageDialog(null, "É obrigatório preencher o campo Senha!");
            return false;
        } else {
            return true;
        }

    }

    private void Salvar() {
        try {
            if (ChecarCampos()) {
                UsuarioModel usuario = new UsuarioModel();
                usuario.setUSUARIO_NOME(txtNome.getText());
                usuario.setUSUARIO_LOGIN(txtLogin.getText());
                usuario.setUSUARIO_SENHA(txtSenha.getText());

                if (usuarioRepository.Salvar(usuario)) {
                    JOptionPane.showMessageDialog(null, "Usuario salvo com sucesso!");
                    txtNome.setText("");
                    txtLogin.setText("");
                    txtSenha.setText("");
                }
                txtNome.grabFocus();
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }

    }

    private void Alterar() {
        try {
            if (ChecarCampos()) {
                UsuarioModel usuario = new UsuarioModel();
                usuario.setUSUARIO_ID(this.IdUsuario);
                usuario.setUSUARIO_NOME(txtNome.getText());
                usuario.setUSUARIO_LOGIN(txtLogin.getText());
                usuario.setUSUARIO_SENHA(txtSenha.getText());

                if (usuarioRepository.Alterar(usuario)) {
                    JOptionPane.showMessageDialog(null, "Usuario alterado com sucesso!");
                    this.dispose();
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        txtSenha = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtLogin = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(153, 153, 0));
        jPanel1.setMinimumSize(new java.awt.Dimension(350, 400));
        jPanel1.setOpaque(false);
        jPanel1.setPreferredSize(new java.awt.Dimension(350, 400));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });
        jPanel1.add(btnSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 280, 97, 50));

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        jPanel1.add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 280, 97, 50));
        jPanel1.add(txtSenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 180, 190, 34));

        jLabel3.setText("Senha:");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 190, 40, 20));
        jPanel1.add(txtLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 120, 190, 34));

        jLabel2.setText("Login:");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 130, 50, 20));
        jPanel1.add(txtNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 60, 190, 34));

        jLabel1.setText("Nome:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 70, 61, 20));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
    if (this.editar == false) {
        Salvar();
    } else {
        Alterar();
    }
}//GEN-LAST:event_btnSalvarActionPerformed

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
    this.dispose();
}//GEN-LAST:event_btnCancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastroUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtSenha;
    // End of variables declaration//GEN-END:variables
}
